//
//  MinePageViewController.m
//  ShowYork
//
//  Created by hxh on 2021/3/5.
//  Copyright © 2021 hxh. All rights reserved.
//

#import <StoreKit/StoreKit.h>
#import "CommonWebViewController.h"
#import "MinePageViewController.h"
#import "HomePageUserLikeListViewController.h"
#import "MineAccountSetViewController.h"
#import "MinePageOpusListViewController.h"
#import "HomeUserInfoDynamicListViewController.h"
#import "MineAccountUpdateDescViewController.h"
#import "MineFollowListViewController.h"
#import "HomePageUserInfoViewController.h"

#import "HomePageTopicListViewController.h"
#import "MinePageHeaderView.h"
#import "MineItemToolView.h"

#import "MineMessaeUnreadCountModel.h"

#import "HomePageUserInfoModel.h"

@interface MinePageViewController ()<MinePageHeaderViewDelegate>
@property (nonatomic,strong)MinePageHeaderView *headerView;
@property (nonatomic,strong)MineItemToolView *toolView;
@property (nonatomic,strong)HomePageUserInfoModel *userInfo;
@property (nonatomic,strong)UIImageView *messageImgView;
@property (nonatomic,strong)UIButton *messageBtn;
@property (nonatomic,strong)UIImageView *backImgView;
@property (nonatomic,strong)UIButton *backBtn;
@end

@implementation MinePageViewController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    

    [self loadMessageUnreadSource];
  
    [self loadUserInfo];
    
    [self updateTabItemIndex];
}



- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setUI];
    // Do any additional setup after loading the view.
}


- (void)setUI{
    
    self.isHideNavBar = YES;
    
    self.edgesForExtendedLayout = UIRectEdgeNone;
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.headerView = [[MinePageHeaderView alloc]init];
    self.headerView.delegate = self;
    [self.view addSubview:self.headerView];
    
    [self.headerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(kNavBarHeight);
        make.left.right.equalTo(self.view);
    }];
    
    __weak typeof(self)weakSelf = self;
    self.toolView = [[MineItemToolView alloc]initWithItemTitles:@[@"家长监管",@"意见反馈",@"给我评分",@"设置"] itemIcons:@[@"mine_parent_tag",@"mine_feedback_tag",@"mine_score_tag",@"home_set_tag"] completeBlock:^(NSInteger index) {
        if (index == 0) {
            [MobClick event:@"parent_monitor_show"];
            CommonWebViewController *webVC = [[CommonWebViewController alloc]init];
            webVC.isDark = NO;
            webVC.webUrl = [NSString stringWithFormat:@"%@wx/parentCode?userId=%@&navbar=no",HtmlUrl,[RPAppManager getCustomerId]];
            webVC.title = @"家长监管";
            [weakSelf.navigationController pushViewController:webVC animated:YES];
            
        }
        if (index == 1) {
            [MobClick event:@"mine_feedback_show"];
            [MGJRouter openURL:@"local://ddup/mine/feedback" withUserInfo:@{@"navigationVC":self.navigationController} completion:nil];
        }
        if (index == 2) {
            [MobClick event:@"mine_apple_score_click"];
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"https://apps.apple.com/cn/app/dd-up/id1537342377?mt=8"] options:@{} completionHandler:^(BOOL success) {}];
        }
        if (index == 3) {
            [MobClick event:@"mine_set_click"];
            [MGJRouter openURL:@"local://ddup/mine/set" withUserInfo:@{@"navigationVC":self.navigationController,@"block":^(void){
                UserInfoModel *userInfo = [UserInfoModel userInfo];
                weakSelf.userInfo.realName = userInfo.realName;
                weakSelf.userInfo.sex = userInfo.sex;
                [weakSelf.headerView setUserInfo:weakSelf.userInfo];
            },} completion:nil];
        }
    }];
    [self.view addSubview:self.toolView];
    [self.toolView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.headerView.mas_bottom).offset(24);
        make.left.equalTo(self.view).offset(16);
        make.right.equalTo(self.view).offset(-16);
    }];
    
    self.messageImgView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"mine_message_read_tag"]];
    self.messageImgView.highlightedImage = [UIImage imageNamed:@"mine_message_unread_tag"];
    [self.view addSubview:self.messageImgView];
    
    self.messageBtn = [[UIButton alloc]init];
    [self.messageBtn addTarget:self action:@selector(messageMethod) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.messageBtn];
    [self.messageImgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.view).offset(-16);
        make.top.equalTo(self.view).offset(GK_STATUSBAR_HEIGHT + 12);
        make.size.mas_equalTo(CGSizeMake(20, 20));
    }];
    [self.messageBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.messageImgView).offset(-8);
        make.right.equalTo(self.messageImgView.mas_right).offset(16);
        make.top.equalTo(self.view).offset(GK_STATUSBAR_HEIGHT);
        make.bottom.equalTo(self.messageImgView.mas_bottom).offset(8);
    }];
    
    self.backImgView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"common_back_tag"]];
    [self.view addSubview:self.backImgView];
    
    self.backBtn = [[UIButton alloc]init];
    [self.backBtn addTarget:self action:@selector(backMethod) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.backBtn];
    [self.backImgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(16);
        make.top.equalTo(self.view).offset(GK_STATUSBAR_HEIGHT + 12);
        make.size.mas_equalTo(CGSizeMake(20, 20));
    }];
    [self.backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.backImgView).offset(-8);
        make.right.equalTo(self.backImgView.mas_right).offset(16);
        make.top.equalTo(self.view).offset(GK_STATUSBAR_HEIGHT);
        make.bottom.equalTo(self.backImgView.mas_bottom).offset(8);
    }];
    
}

- (void)updateTabItemIndex{
    if([[NSUserDefaults standardUserDefaults] stringForKey:@"tabItemIndex"].length > 0){
        NSInteger index = [[[NSUserDefaults standardUserDefaults] objectForKey:@"tabItemIndex"]intValue];
        [self.tabBarController setSelectedIndex:index];
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"tabItemIndex"];
    }
}

#pragma mark - action
- (void)backMethod{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)messageMethod{
    [MobClick event:@"mine_message_show"];
    [MGJRouter openURL:@"local://ddup/mine/messageList" withUserInfo:@{@"navigationVC":self.navigationController} completion:nil];
}

#pragma mark - network

- (void)loadMessageUnreadSource{
    if (![RPAppManager isLogin]) {
        return;
    }
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"userId"] = [RPAppManager getCustomerId];
    param[@"md5"] = [RPAppManager md5StrWithApi:MessageTypeUnRead];
    [[RPNetworkExtensionTool sharedTool ]requestPOST:kGET_REQUEST_URL(MessageTypeUnRead) parames:param success:^(id responseObj) {
        NSArray *resultArray = [MineMessaeUnreadCountModel mj_objectArrayWithKeyValuesArray:responseObj[RESPONSE]];
       
        __block BOOL isUnreadMessage = NO;
        __block NSInteger maxUnreadCount = 0;
        [resultArray enumerateObjectsUsingBlock:^(MineMessaeUnreadCountModel *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            maxUnreadCount+=obj.messageUrNum.intValue;
            if (obj.messageUrNum.intValue > 0) {
                isUnreadMessage = YES;
            }
        }];
//        if (isUnreadMessage) {
//            [self.tabBarController.tabBar showBadgeOnItemIndex:3];
//        }else{
//            [self.tabBarController.tabBar hideBadgeOnItemIndex:3];
//        }
        self.messageImgView.highlighted = isUnreadMessage;
        [[NSUserDefaults standardUserDefaults]setObject:@(isUnreadMessage) forKey:@"messageReadStatus"];
        [[NSUserDefaults standardUserDefaults]setObject:@(maxUnreadCount) forKey:@"messageUnReadCount"];
        [[NSUserDefaults standardUserDefaults]synchronize];
        
    } failure:^(id error) {
            
    }];
}
- (void)loadUserInfo{
    
    if (![RPAppManager isLogin]) {
        return;
    }
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"postId"] = [RPAppManager getCustomerId];
    if ([RPAppManager getCustomerId].intValue != 0) {
        param[@"userId"] = [RPAppManager getCustomerId];
    }
    param[@"md5"] = [RPAppManager md5StrWithApi:GetTopInfo];
    [[RPNetworkExtensionTool sharedTool] requestPOST:kGET_REQUEST_URL(GetTopInfo) parames:param success:^(id responseObj) {
        
        self.userInfo = [HomePageUserInfoModel mj_objectWithKeyValues:responseObj[RESPONSE]];
    
        self.headerView.userInfo = self.userInfo;

    } failure:^(NSError *error) {
       
    }];
}



#pragma mark - delegate

- (void)showUserInfoFansList{
    
    UserInfoModel *userInfo = [UserInfoModel userInfo];
    
    MineFollowListViewController *followVC = [[MineFollowListViewController alloc]initWithUserInfoId:[RPAppManager getCustomerId] userName:userInfo.realName index:0];
    [self.navigationController pushViewController:followVC animated:YES];
}
- (void)showUserInfoOpusList{
    MinePageOpusListViewController *listVC = [[MinePageOpusListViewController alloc]init];
    [self.navigationController pushViewController:listVC animated:YES];
}
- (void)showUserInfoDynamicList{
    HomeUserInfoDynamicListViewController *listVC = [[HomeUserInfoDynamicListViewController alloc]init];
    listVC.userId = [RPAppManager getCustomerId];
    [self.navigationController pushViewController:listVC animated:YES];
}
- (void)showUserInfoLikedList{
    HomePageUserLikeListViewController *listVC = [[HomePageUserLikeListViewController alloc]init];
    listVC.userId = [RPAppManager getCustomerId];
    [self.navigationController pushViewController:listVC animated:YES];
}
- (void)showUserInfo{
    [MobClick event:@"mine_user_show"];
    HomePageUserInfoViewController *vc = [[HomePageUserInfoViewController alloc]initWithUserId:[RPAppManager getCustomerId]];
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)updateUserDesc{
    MineAccountUpdateDescViewController *vc = [[MineAccountUpdateDescViewController alloc]init];
    [self.navigationController pushViewController:vc animated:YES];

}



@end
